<?php
/**
 * (jobs) 预估
 */
namespace App\Jobs\Stocking;

use App\Models\SsBasic\AreaSkuEstimate;
use App\Models\Stocking\StockingSku;
use App\Models\Stocking\StockingSkuRatio;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class Estimate implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $estimate;

    /**
     * Estimate constructor.
     * @param $estimate
     */
    public function __construct($estimate)
    {
        $this->estimate = $estimate;
    }

    /**
     * Execute the job.
     * @return void
     */
    public function handle()
    {
        $this->exeFillData($this->estimate);
    }

    private function exeFillData($estimate){
        foreach ($estimate as $_estimate){
            $classifyId = $_estimate->classify_id;
            //备货sku
            $ss = StockingSku::query()
                ->where('area_id',$_estimate->area_id)
                ->whereHas('sku',function ($query) use ($classifyId){
                    $query->where('classify_id',$classifyId);
                })
                ->get();
            foreach ($ss as $_ss){
                $key = $_ss->area_id.'_'.$_ss->psku_id;
                $ratio = StockingSkuRatio::getRatio($key);

                //站点预估
                $ase = AreaSkuEstimate::query()->firstOrNew(['area_psku' => $key]);
                for($i = 0;$i < AreaSkuEstimate::ESTIMATE_NUM;$i++){
                    $num = $_estimate->{'estimate_num'.$i} ?? 0; //赋值
                    $estimateNum = intval(round($num * $ratio));
                    $_ss->{'estimate_num'.$i} = $estimateNum;
                    $ase->{'estimate_num'.$i} = $estimateNum;
                }
                $_ss->save();
                $ase->save();

                $_ss->over_stock = StockingSku::getOverStock($_ss);
                $_ss->over_stock_value = StockingSku::getOverStockValue($_ss->over_stock,$_ss->unit_price);
                $_ss->save();
            }
        }
    }
}
